#import "RCChoice.h"
#import "RCChoiceUpdater.h"
#import "RCChoiceFileHandler.h"
#import "RCPrefsWindowController.h"
#import "RCChoiceTableController.h"

@implementation RCChoice

- (IBAction)fileOpen:(id)sender
{
	RCChoiceFileHandler *fileHandler = [[RCChoiceFileHandler alloc] init];
	//Create a new file handler instance
	NSOpenPanel *oPanel = [NSOpenPanel openPanel];
	NSArray *fileTypes = [NSArray arrayWithObjects:@"cresults",nil];
	oPanel = [NSOpenPanel openPanel];
	[oPanel setCanChooseDirectories:NO];
	[oPanel setCanChooseFiles:YES];
	[oPanel setCanCreateDirectories:YES];
	[oPanel setAllowsMultipleSelection:NO];
	[oPanel setTitle:@"Select a results file to open"];
	//Show open panel for loading results
	if([oPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes] == NSOKButton){
		[splashWindow orderOut:nil];
		//Hide welcome window and load results nib file if not already loaded
		if(!infoPanelController){
			[NSBundle loadNibNamed:@"Results" owner:self];
			infoPanelController = [[NSWindowController alloc] initWithWindow:infoPanel];
		}
		//Show results window
		[infoPanelController showWindow:self];
		NSArray *fileDir = [oPanel filenames];
		//Get answers from results file and set the listbox datasource to the array
		NSMutableArray* Answers = [[NSMutableArray alloc] initWithArray:[fileHandler getAnswers:[fileDir objectAtIndex:0]]];
		[table setItems:Answers];
		int right = [fileHandler getTotalRightAnswers:[fileDir objectAtIndex:0]];
		int wrong = [fileHandler getTotalWrongAnswers:[fileDir objectAtIndex:0]];
		int count = right + wrong;
		NSMutableString *result = [[NSMutableString alloc] init];
		[result appendString:[NSString stringWithFormat:@"You answered %d/%d questions correctly, look below for details.",right,count]];
		[txResult setStringValue:result];
	}
}
- (IBAction)fileStart:(id)sender
{
	RCChoiceFileHandler *fileHandle = [[RCChoiceFileHandler alloc] init];
	if([fileHandle loadTest])
	{
		[splashWindow  orderOut:nil];
		NSArray* tempArray = [fileHandle getTestQA];
		infoArray = [fileHandle getTestInfo];
		NSString* title = [[[infoArray objectAtIndex:1] stringByAppendingString:@" - "] stringByAppendingString:[infoArray objectAtIndex:2]];
		[testWindow makeKeyAndOrderFront:nil];
		[testWindow setTitle:title];
		[testWindow setDocumentEdited:YES];
		qArray = [[NSArray alloc] initWithArray:tempArray];
		ansArray = [[NSMutableArray alloc] init];
		strQuestion = [qArray objectAtIndex:0];
		[txQuestion setStringValue:strQuestion];
		strAnswer = [qArray objectAtIndex:1];
		[ansArray addObject:strAnswer];
		counter++;
		aArray = [[NSMutableArray alloc] init];
		arrCount = [qArray count];
		arrCount--;
		testStarted = true;
	}
}

- (IBAction)set:(id)sender
{
	if(testStarted == true){
		if(counter < arrCount){
			counter++;
			strQuestion = [qArray objectAtIndex:counter];
			counter++;
			strAnswer = [qArray objectAtIndex:counter];
			[aArray addObject:[txAnswer stringValue]];
			[ansArray addObject:strAnswer];
			[txQuestion setStringValue:strQuestion];
			[txAnswer setStringValue:@""];
		}
		else{
			[aArray addObject:[txAnswer stringValue]];
			testStarted = false;
			[txQuestion setStringValue:@""];
			[txAnswer setStringValue:@""];
			counter = 0;
			strQuestion = @"";
			strAnswer = @"";
			int count;
			int condition = [aArray count];
			NSMutableArray *rightAnswers = [[NSMutableArray alloc] init];
			NSMutableArray *wrongAnswers = [[NSMutableArray alloc] init];
			NSString *right;
			NSString *wrong;
			for(count = 0;count < condition;count++)
			{
				right = [aArray objectAtIndex:count];
				wrong = [ansArray objectAtIndex:count];
				BOOL result = [right caseInsensitiveCompare:wrong] == NSOrderedSame;
				if(result == YES){
					[rightAnswers addObject:[[@"Your answer '" stringByAppendingString:[aArray objectAtIndex:count]] stringByAppendingString:@"' was correct."]];
				}
				else{
					[wrongAnswers addObject:[[[[@"Your answer '" stringByAppendingString:[aArray objectAtIndex:count]] stringByAppendingString:@"' was incorrect, the correct answer was '"] stringByAppendingString:[ansArray objectAtIndex:count]] stringByAppendingString:@"'."]];
				}
			}
			RCChoiceFileHandler *fileHandler = [[RCChoiceFileHandler alloc] init];
			NSArray *rAnswers = [[NSArray alloc] initWithArray:rightAnswers];
			NSArray *wAnswers = [[NSArray alloc] initWithArray:wrongAnswers];
			if([fileHandler saveResults:rAnswers wrongAnswers:wAnswers testInfo:infoArray] == YES){
				//NSRunCriticalAlertPanel(@"Error",@"Choice was unable to save your results file.",@"OK",nil,nil,nil,nil);			
				//MAJOR FIX - use initwithstring to prevent distruction at end of function!
				resultsp = [[NSString alloc] initWithString:[fileHandler getResultPath]]; 
				NSString *title = @"Test Finished";
				NSString *defaultButton = @"Finish";
				NSString *alternateButton = @"Show Results";
				NSString *message = @"Your test is now finished, you can either close this window or show the results of your test now.";
				NSBeginAlertSheet(title, defaultButton, alternateButton, nil, testWindow, self, @selector(sheetDidEnd:returnCode:contextInfo:), @selector(sheetHadDismiss:returnCode:contextInfo:), nil, message);
			}
			else{
				[testWindow orderOut:nil];
			}
		}
	}
}

- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
	if ( returnCode == NSAlertAlternateReturn ){
		if(!infoPanelController){
			[NSBundle loadNibNamed:@"Results" owner:self];
			infoPanelController = [[NSWindowController alloc] initWithWindow:infoPanel];
		}
		[infoPanelController showWindow:self];
		NSString *path;
		RCChoiceFileHandler *fileHandler = [[RCChoiceFileHandler alloc] init];
		NSMutableArray* Answers;
		if([[NSUserDefaults standardUserDefaults] objectForKey:@"saveResultsHome"] == @"1"){
			path = [[[[[NSHomeDirectory() stringByAppendingString:@"/"] stringByAppendingString:[infoArray objectAtIndex:1]] stringByAppendingString:@" - "] stringByAppendingString:[infoArray objectAtIndex:2]] stringByAppendingString:@".cresults"];
		}
		else
		{
			path = resultsp;
		}
		Answers = [[NSMutableArray alloc] initWithArray:[fileHandler getAnswers:path]];
		[table setItems:Answers];
		int right = [fileHandler getTotalRightAnswers:path];
		int wrong = [fileHandler getTotalWrongAnswers:path];
		int count = right + wrong;
		NSMutableString *result = [[NSMutableString alloc] init];
		[result appendString:[NSString stringWithFormat:@"You answered %d/%d questions correctly, look below for details.",right,count]];
		[txResult setStringValue:result];
	}
}

- (void)sheetHadDismiss:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
	[testWindow orderOut:nil];
}

- (IBAction)showHelp:(id)sender
{
	[[NSHelpManager sharedHelpManager] openHelpAnchor:@"Using the Test Window" inBook:@"Choice"];  
}

- (IBAction)showHelpMain:(id)sender
{
	[[NSHelpManager sharedHelpManager] openHelpAnchor:@"Choice Overview" inBook:@"Choice"];
}

- (IBAction)resultsFinish:(id)sender
{
	[infoPanelController close];
}

- (IBAction)fileLicense:(id)sender
{
	NSOpenPanel *dirLicense = [NSOpenPanel openPanel];
	[dirLicense setCanChooseDirectories:NO];
	[dirLicense setCanChooseFiles:YES];
	[dirLicense setCanCreateDirectories:YES];
	[dirLicense setAllowsMultipleSelection:NO];
	[dirLicense setTitle:@"Select a license file"];
	NSArray *fileTypes = [NSArray arrayWithObjects:@"rclc", nil];
	int result = [dirLicense runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes];
	if (result == NSOKButton) {
		NSArray *fileDir = [dirLicense filenames];
		RCChoiceUpdater *licenseVerify = [[RCChoiceUpdater alloc] init];
		result = [licenseVerify verifyLicense:[fileDir objectAtIndex:0]];
		if (result == true) {
			NSString *msg = [@"Hi " stringByAppendingString:[licenseVerify returnLicenseName:[fileDir objectAtIndex:0]]];
			msg = [msg stringByAppendingString:@", thanks for registering this application, it will be valid for all future minor updates and bug fixes."];
			NSRunAlertPanel(@"License Validation",msg,@"OK",nil,nil,nil,nil);
			if ([mnuRegister isEnabled] == YES){
				[mnuApp setAutoenablesItems:NO];
				[mnuRegister setEnabled:NO];
				[[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"appRegistered"];
				[[NSUserDefaults standardUserDefaults] setObject:[licenseVerify returnLicenseName:[fileDir objectAtIndex:0]] forKey:@"appRegisteredName"];
			}
		}
		else{
			NSRunAlertPanel(@"License Validation",@"Your license is invalid, if this is a mistake please contact technical support.",@"OK",nil,nil,nil,nil);
		}
	}
}

- (IBAction)openPreferencesWindow:(id)sender
{
	[[RCPrefsWindowController sharedPrefsWindowController] showWindow:nil];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
//  if ([[NSUserDefaults standardUserDefaults] boolForKey:@"appRegistered"]) {
		[mnuApp setAutoenablesItems:NO];
		[mnuRegister setEnabled:NO];
//  }
  if ([[NSUserDefaults standardUserDefaults] boolForKey:@"showSplash"]){
		[splashWindow makeKeyAndOrderFront:nil];
  }
}

+ (void)initialize
{
	[[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"showSplash"];
	[[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"saveResultsHome"];
}

@end
